package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.utils.EmptyUtility;
import com.honey.mybatis.generator.MybatisPlugin;

public class DeleteByPrimaryKey extends AbstractMybatisMapper{

	public DeleteByPrimaryKey(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		List<TableColumn> list = null;
		
		if( schema instanceof Table ){
			IntrospectTableColumn introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
			if( EmptyUtility.isListEmpty(introspectTableColumn.primaryKeyColumns()))
				return ;
			else
				list = introspectTableColumn.primaryKeyColumns();
		}
		
		parent.addNewLine();
		parent.addComments(
				"按照主键删除记录"
		);
		//String var_entity_name =  super.getEntityClassName(schema);
		XmlElement delete = new XmlElement(parent,"delete")
		.addAttribute("id",MapperConstant.DELETE_BY_PRIMARY_KEY_MAPPER_ID)
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addAttribute("flushCache", "true");
		if( list.size() ==1){
			delete.addAttribute("parameterType",list.get(0).getFullyQualifiedJavaType().getLongName());
		}else{
			delete.addAttribute("parameterType","map");
		}
		
		delete.addTextElement("DELETE FROM "+schema.getName());
		
		StringBuilder sb = new StringBuilder().append("WHERE ");
		boolean comma = false;
		for(TableColumn column : list ){
			if (comma)sb.append(" AND "); else comma = true;
			sb.append(column.getName()).append(" = #{")
			.append(column.getJavaProperty()).append(",jdbcType=").append(JdbcTypeName.getJdbcTypeName(column.getJdbcType()))
			.append("}");
		}
		delete.addTextElement(sb.toString());
	}
}
